﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
using Davidwang;

/// <summary>
/// 手势控制器(使用了 Manipulator，暂时禁用)
/// 1. 检测到平面后点击放置虚拟物体，然后可以进行手势操作
/// 2. 检测到图像后放置物体，然后可进行手势操作(暂时无法实现,
/// </summary>
[RequireComponent(typeof(ARRaycastManager))]
public class GestureController : MonoBehaviour
{
    public GameObject spawnPrefab;
    public GameObject manipulator;
    static List<ARRaycastHit> Hits;
    private ARRaycastManager mRaycastManager;
    private int maxNum = 3;

    private void Start()
    {
        Hits = new List<ARRaycastHit>();
        mRaycastManager = GetComponent<ARRaycastManager>();
    }

    void Update()
    {
        addPrefabOnClick();
    }

    private void addPrefabOnClick()
    {
        if (Input.touchCount == 0)
            return;
        var touch = Input.GetTouch(0);
        if (mRaycastManager.Raycast(touch.position, Hits, TrackableType.PlaneWithinPolygon | TrackableType.PlaneWithinBounds))
        {
            var hitPose = Hits[0].pose;
            if (maxNum > 0)
            {
                var spawnedObject = Instantiate(spawnPrefab, hitPose.position, hitPose.rotation);
                var maniObject = Instantiate(manipulator, hitPose.position, hitPose.rotation);
                addPrefab(spawnedObject, maniObject, gameObject);
                maxNum--;
            }
        }
    }

    public void addPrefab(GameObject spawnedObject, GameObject maniObject, GameObject maniParentObject)
    {
        spawnedObject.transform.parent = maniObject.transform;
        maniObject.transform.parent = maniParentObject.transform;
        maniObject.GetComponent<Manipulator>().Select();
    }
}